<template>
  <div class="menu-manager">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增菜单</el-button>
    </div>
    
    <el-table
      :data="menuList"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'children' }"
      draggable
      @row-drop="handleDrop">
      <el-table-column prop="name" label="菜单名称" />
      <el-table-column prop="icon" label="图标">
        <template #default="{ row }">
          <el-icon v-if="row.icon"><component :is="row.icon" /></el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="perms" label="权限标识" />
      <el-table-column prop="component" label="组件路径" />
      <el-table-column prop="type" label="类型">
        <template #default="{ row }">
          <el-tag v-if="row.type === 'M'">目录</el-tag>
          <el-tag v-else-if="row.type === 'C'" type="success">菜单</el-tag>
          <el-tag v-else-if="row.type === 'A'" type="warning">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleAdd(row)">添加子菜单</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 菜单表单对话框 -->
    <el-dialog
      :title="formTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      destroy-on-close>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px">
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="form.pid"
            :data="menuOptions"
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择上级菜单"
            clearable />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="perms">
          <el-input v-model="form.perms" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="A">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/api'

const menuList = ref([])
const dialogVisible = ref(false)
const formTitle = ref('')
const formRef = ref()
const form = ref({
  id: null,
  pid: 0,
  name: '',
  icon: '',
  perms: '',
  component: '',
  type: 'M',
  sort: 0
})

const rules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  sort: [{ required: true, message: '请输入显示排序', trigger: 'blur' }]
}

// 菜单树选项
const menuOptions = ref([])

// 获取菜单列表
const getMenuList = async () => {
  try {
    const res = await adminAPI.getMenus()
    menuList.value = res.data
    menuOptions.value = [{ id: 0, name: '主目录', children: res.data }]
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  }
}

// 新增菜单
const handleAdd = (row) => {
  formTitle.value = '新增菜单'
  form.value = {
    id: null,
    pid: 0,  // 始终默认为0
    name: '',
    icon: '',
    perms: '',
    component: '',
    type: 'M',
    sort: 0
  }
  
  // 如果是通过"添加子菜单"按钮触发，则设置父级ID
  if (row) {
    form.value.pid = row.id
  }
  
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  formTitle.value = '编辑菜单'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该菜单吗？', '提示', {
      type: 'warning'
    })
    await adminAPI.deleteMenu(row.id)
    ElMessage.success('删除成功')
    getMenuList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (form.value.id) {
      await adminAPI.updateMenu(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await adminAPI.createMenu(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    getMenuList()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 处理拖拽
const handleDrop = async ({ newIndex, oldIndex, row }) => {
  try {
    await adminAPI.moveMenu(row.id, row.pid, newIndex)
    ElMessage.success('移动成功')
    getMenuList()
  } catch (error) {
    console.error('移动菜单失败:', error)
  }
}

onMounted(() => {
  getMenuList()
})
</script>

<style scoped>
.menu-manager {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}
</style>